package bid.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
public class StringUtils {
    private StringUtils() {
    }

    /**
     * 判断o是不是空
     *
     * @param o
     * @return
     */
    public static boolean isNotBlank(Object o) {
        return o != null && String.valueOf(o).length() > 0;
    }

    /**
     * 把字符串转换成日期格式，如果转换失败，返回null
     *
     * @param s
     * @return
     */
    private static final SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd");

    public static Date toDate(String s) {
        try {
            return DF.parse(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    public static String toStr(Date s) {
        try {
            return DF.format(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    public static String trim(Object s) {
        if (s == null)
            return "";
        return String.valueOf(s).trim();//去空格
    }

    public static int toInt(String s, int def) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return def;
    }
    public static int toInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return 0;
    }
    public static double toDouble(String s) {
        try {
            return Double.parseDouble(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return 0;
    }
    public static long toLong(String s) {
        try {
            return Long.parseLong(s);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return 0;
    }
    public static String md5(String str) {
        byte[] digest = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest = md5.digest(str.getBytes("utf-8"));
        } catch (Exception e) {
        }
//16是表示转换为16进制数
        String md5str = new BigInteger(1, digest).toString(16);
        return md5str;
    }
}
